package com.qining618.cms.cms.service.impl;

import com.qining618.cms.cms.domain.Channel;
import com.qining618.cms.cms.mapper.ChannelContentMapper;
import com.qining618.cms.cms.mapper.ChannelMapper;
import com.qining618.cms.cms.service.ChannelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qining618.common.exception.BusinessException;
import com.qining618.common.result.ErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * CMS栏目表 服务实现类
 * </p>
 *
 * @author qining
 * @date 2019-09-17
 */
@Transactional(readOnly = true, rollbackFor = Exception.class)
@Service
public class ChannelServiceImpl extends ServiceImpl<ChannelMapper, Channel> implements ChannelService {

    @Autowired
    private ChannelContentMapper channelContentMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Channel add(String name, String link, Integer priority, Boolean isDisplay) {
        Channel channel = new Channel();
        channel.setName(name).setLink(link).setPriority(priority).setIsDisplay(isDisplay);
        int opNum = this.baseMapper.insert(channel);
        if (opNum != 1) {
            throw new BusinessException(ErrorCode.DB_ERROR);
        }
        return channel;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Channel edit(Long id, String name, String link, Integer priority, Boolean isDisplay) {
        Channel channel = this.baseMapper.selectById(id);
        if (channel == null) {
            throw new BusinessException(ErrorCode.DATA_NOT_FOUND, "栏目不存在");
        }
        channel.setName(name).setLink(link).setPriority(priority).setIsDisplay(isDisplay);

        int opNum = this.baseMapper.updateById(channel);
        if (opNum != 1) {
            throw new BusinessException(ErrorCode.DB_ERROR);
        }
        return channel;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteById(Long id) {
        // 删除栏目内容关联
        this.channelContentMapper.deleteByChannelId(id);

        // 删除栏目
        int opNum = this.baseMapper.deleteById(id);
        if (opNum != 1) {
            throw new BusinessException(ErrorCode.DB_ERROR);
        }
    }
}
